<?php
/**
 * Created by PhpStorm.
 * User: lance
 * Date: 2017/10/26
 * Time: 17:44
 */

namespace app\customer\admin;


use app\admin\controller\Admin;
use app\customer\model\Loan;
use app\common\builder\ZBuilder;
use app\common\log\turnCustomer\TurnCustomer;
use app\customer\model\Customer;
use php_excel\libs\Excel;
use php_identify\libs\CharacterIdentify;
use php_identify\libs\HobbyIdentify;
use php_identify\libs\IdCardIdentify;
use php_identify\libs\Identify;
use php_identify\libs\NameIdentify;
use php_identify\libs\NumberIdentify;
use php_identify\libs\SexIdentify;
use php_identify\libs\TradesIdentify;
use think\Db;
use think\Url;
use app\common\log\addRole\CustomerAdd;

class Customers extends Admin
{
    private $a_data;

    /**
     * 客户列表
     * @return mixed
     */
    public function index()
    {
        $a_fields = [
            'a.id id', 'a.name name', 'a.turn_status turn_status', 'a.sex sex', 'a.cert_type cert_type', 'a.level_id',
            'a.cert_number cert_number', 'a.tel1 tel1', 'a.trade', 'a.career',
            'b.name manager_name',
        ];
        $a_where = $this->getMap();//表头筛选
        foreach ($a_where as $s_key => $a_val):
            switch ($s_key):
                case 'customer.name':
                    $a_where['a.name'] = $a_val;
                    unset($a_where[$s_key]);
                    break;
                case 'customer.sex':
                    $a_where['a.sex'] = $a_val;
                    unset($a_where[$s_key]);
                    break;
                case 'manager.name':
                    $a_where['b.name'] = $a_val;
                    unset($a_where[$s_key]);
                    break;
                case 'customer.turn_status':
                    $a_where['a.turn_status'] = $a_val;
                    unset($a_where[$s_key]);
                    break;
            endswitch;
        endforeach;
        //客户经理只能看自己的客户
        if (ROLE_ID == 3):
            $a_where['a.manager_id'] = Db::name('admin_user')->where('id', UID)->value('role_id');
        elseif (ROLE_ID == 2):
            //领导查看对应网点客户经理的客户

            //管理的网点
            $s_netsites = Db::name('manager')->where('number', session('user_auth.username'))->value('net_name');
            //获取对应的网点名
            $a_netsites = Db::name('netsite_record')->where('id', 'in', $s_netsites)->column('net_name');
            //获取对应网点的客户经理
            if (empty($a_netsites)):
                $a_managerIds = [-1];
            else:
                $a_managerIds = Db::name('manager')->where('net_name', 'in', $a_netsites)->column('id');
            endif;
            if (empty($a_managerIds)):
                $a_where['a.manager_id'] = -1;
            else:
                $a_where['a.manager_id'] = ['in', $a_managerIds];
            endif;
        endif;
        $a_dataList = Db::name('customer a')->field($a_fields)
            ->join('manager b', 'a.manager_id=b.id', 'LEFT')
            ->where($a_where)
            ->order('id desc')->paginate();
        $s_tips = <<<EOT
1.客户移交，超级管理员和领导可直接进行客户移交，客户经理进行客户移交先会进行移交申请,需要另一方客户经理同意。
<br/>
2.客户移交，处于移交状态的客户无法再次发起移交，需要等到移交处理完成!
<br/>
3.用户贷款，在操作栏也可以进行用户贷款数据添加。
EOT;
        //客户分组
        $a_group = Db::name('customer_level')->where('status', 1)->column('id,name');
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addFilter([
                'name' => 'customer',
                'sex' => 'customer',
                'turn_status' => 'customer',
                'manager_name' => 'manager.name',
            ])
            ->addFilterList('level_id', $a_group, '', 'radio')
            ->addFilterList('customer.turn_status', ['正在移交', '正常状态'], '', 'radio')
            ->setSearch([
                'a.name' => '客户名',
                'b.name' => '客户经理',
            ])
            ->addFilterMap('name', 'manager_name')
            ->addFilterMap('manager_name', 'name')
            ->addColumns(config('customer_list'))
            ->addColumn('manager_name', '所属客户经理')
            ->addColumn('turn_status', '移交状态', 'status', '', ['正在移交', '正常状态'])
            ->addColumn('level_id|customer.level_id', '客户分组', 'select', $a_group)
            ->addColumn('right_button', '操作', 'btn')
            ->setPageTips($s_tips)
            ->setRowList($a_dataList)
            ->addRightButton('custom', [
                'title' => '查看客户资料',
                'icon' => 'glyphicon glyphicon-eye-open',
                'href' => url('showinfo', [
                    'id' => '__id__'
                ])
            ], true)
            ->addRightButton('edit')
            ->addRightButton('custom',
                [
                    'title' => '移交客户',
                    'icon' => 'fa fa-fw fa-arrow-right',
                    'href' => url('turnCustomer', ['id' => '__id__'])
                ])
            ->addRightButton('custom',
                [
                    'title' => '添加客户贷款',
                    'icon' => 'fa fa-fw fa-plus',
                    'href' => url('loan/addLoanItem',
                        ['customer_id' => '__id__']
                    )
                ])
            ->addRightButton('custom',
                [
                    'title' => '添加客户存款',
                    'icon' => 'glyphicon glyphicon-plus',
                    'href' => url('deposit/add', [
                        'customer_id' => '__id__'
                    ])
                ]
            )
            ->fetch();
    }

    public function edit($id = '')
    {
        if (request()->isAjax()):
            $this->a_data = input('');
            $o_validate = new \app\customer\validate\Customer();
            if ($o_validate->check($this->a_data) === false):
                $this->error($o_validate->getError());
            endif;
            $o_model = new \app\customer\model\Customer();
            if ($o_model->isUpdate()->save($this->a_data) === false):
                //更新失败记录日志
                $a_logData = [
                    'role_id' => $id,
                    'status' => 0,
                    'type' => 1,//添加用户
                    'error' => '',
                    'update' => true,
                    'content' => json_encode($this->a_data)
                ];
                $o_obj = new CustomerAdd($a_logData);
                $o_obj->addOne();
                $this->error("更新失败！");
            else:
                //更新失败记录日志
                $a_logData = [
                    'role_id' => $id,
                    'status' => 1,
                    'type' => 1,//添加用户
                    'update' => true,
                    'error' => '',
                    'content' => json_encode($this->a_data)
                ];
                $o_obj = new CustomerAdd($a_logData);
                $o_obj->addOne();
                $this->success("更新成功！");
            endif;
        endif;
        $a_items = config('customer_info');
        return ZBuilder::make('form')
            ->addHidden('id', $id)
            ->addFormItems($a_items)
            ->setFormData(Db::name('customer')->where('id', $id)->find())
            ->fetch();
    }

    /**
     * 查看客户资料
     * @return mixed
     */
    public function showInfo()
    {
        $i_customerId = input('id/d', 0);
        //客户基本信息
        $a_customer = Db::name('customer')->where('id', $i_customerId)->find();
        $a_customer_info = config('customer_info');
        array_shift($a_customer_info);
        //客户分配记录
        $a_dis = Db::name('distribute_customer_log a')
            ->field([
                'b.name' => 'manager',
                'c.name' => 'customer',
                'a.time' => 'time',
                'a.operate_id',
            ])
            ->join('manager b', 'a.manager_id=b.id')
            ->join('customer c', 'a.customer_id=c.id')
            ->where('a.customer_id', $i_customerId)->find();
        $a_role = Db::name('admin_user')->where('id', $a_dis['operate_id'])->find();
        $s_role = '';
        switch ($a_role['role']):
            case 1:
                $s_role = '超级管理员';
                break;
            case 2:
            case 3:
                $a_tmp = Db::name('manager')->where('id', $a_role['role_id'])->find();
                $s_role = $a_tmp['name'] . '(' . $a_role['role'] == 2 ? '领导' : '客户经理' . ')';
                break;
        endswitch;
        //客户移交历史
        $a_turn = Db::name('customer_turn_log')->where('customer_id', $i_customerId)->order('id desc')->select();
        $a_turn = array_map(function ($a_item) use ($a_customer) {
            $a_tmp = [];
            $a_tmp['customer'] = $a_customer['name'];
            $a_tmp['old_manager'] = Db::name('manager')->where('id', $a_item['old_manager'])->value('name');
            $a_tmp['manager'] = Db::name('manager')->where('id', $a_item['manager_id'])->value('name');
            $a_tmp['start_time'] = date('Y-m-d H:i:s', $a_item['start_time']);
            $a_tmp['time'] = $a_item['time'] ? date('Y-m-d H:i:s', $a_item['time']) : '';
            $a_tmp['status'] = ['正在移交', '移交完成', '拒绝接收'][$a_item['status']];
            return $a_tmp;
        }, $a_turn ?: []);
        //客户贷款记录
        $a_loan = Db::name('customer_loan a')
            ->join('customer c', 'a.customer_id=c.id')
            ->order('time desc')
            ->where([
                'customer_id' => $i_customerId,
            ])->select();
        //客户存款记录
        $a_deposit = Db::name('customer_deposit a')
            ->field('a.number,time,deposit_time,money,c.name')
            ->where('customer_id', $i_customerId)
            ->join('customer c', 'a.customer_id=c.id')
            ->order('time desc')
            ->select();
        return $this->fetch('', [
            'customer' => $a_customer,
            'customer_info' => $a_customer_info,
            'dis_log' => $a_dis,
            'dis_operator' => $s_role,
            'turn_log' => $a_turn,

            'loan_log' => $a_loan,
            'loan_type' => Db::name('customer_loan_type')->column('id,name'),
            'deposit_log' => $a_deposit
        ]);
    }

    /**
     * 移交客户
     */
    function turnCustomer()
    {
        if (request()->isAjax()):
            $a_ids = input('ids/a');
            if (count($a_ids) > 1):
                $this->error("一个用户只能有同时被移交到一个客户经理");
            endif;
            //开始移交
            $s_message = $s_return = '';
            switch (ROLE_ID):
                case 1:
                    $s_message = '超级管理员移交客户资料';
                    $s_return = '移交成功';
                    break;
                case 2:
                    $s_message = '领导移交客户资料';
                    $s_return = '移交成功';
                    break;
                case 3:
                    $s_message = '客户经理申请移交客户资料';
                    $s_return = '移交申请成功,请等待客户经理接收';
                    break;
            endswitch;
            $o_turn = new TurnCustomer([
                'customer_id' => input('id/d', 0),
                'manager_id' => $a_ids[0],
                'message' => $s_message
            ]);
            if (($rsl = $o_turn->disOne()) !== true):
                $this->error($rsl);
            else:

                $this->success($s_return, url('index'));
            endif;
        else:
            $i_id = input('id/d', 0);//客户id
            $a_customer = Db::name('customer')->where('id', $i_id)->find();
            //检查客户是否存在
            if (empty($a_customer)):
                $this->error("客户不存在！");
            endif;
            //客户是否处于移交状态
            if (Db::name('customer_turn_log')->where([
                'customer_id' => $i_id,
                'status' => 0,
                'next_log' => 0
            ])->find()):
                $this->error("客户正处于移交状态，请等待处理完成！");
            endif;
            $a_where = [
                'type' => 0,
            ];
            //如果角色是客户经理，则不能移交给自己
            if (ROLE_ID == 3):
                $i_managerId = Db::name('admin_user')->where('id', UID)->value('role_id');
                $a_where['id'] = ['neq', $i_managerId];
            endif;
            //所有客户经理
            $a_map = $this->getMap();
            $a_where = array_merge($a_map, $a_where);
            foreach ($a_where as $s_key => $a_val):
                $s_pre = substr($s_key, 0, strpos($s_key, '.'));
                switch ($s_pre):
                    //过滤查找的时候会自动添加表前缀，真正查找时又不添加前缀
                    case 'manager':
                        $a_where['xcmanager' . substr($s_key, strpos($s_key, '.'))] = $a_val;
                        unset($a_where[$s_key]);
                        break;
                endswitch;
            endforeach;
            $a_manger = Db::name('manager')->where($a_where)->paginate();
            return ZBuilder::make('table')
                ->addFilter([
                    'name' => 'manager'
                ])
                ->setPageTips('一个用户只能有同时被移交到一个客户经理', 'warning')
                ->addColumns([
                    ['department', '部门'],
                    ['number', '柜员号'],
                    ['name', '姓名'],
                    ['sex', '性别']
                ])
                ->addTopButton('custom',
                    [
                        'title' => '确认移交',
                        'icon' => 'fa fa-fw fa-arrow-right',
                        'class' => 'btn btn-danger confirm ajax-post',
                        'data-title' => '你确认移交吗？',
                        'data-tips' => '移交后可在日志管理中查看客户移交日志',
                        'href' => url('', ['id' => $i_id])
                    ])
                ->setRowList($a_manger)
                ->fetch();
        endif;
    }

    /**
     * 随机生成客户
     */
    public function createCustomers()
    {
        set_time_limit(0);
        $i_nums = 10;
        $i_sign = 1;
        $o_person = new Identify();
        $o_name = new NameIdentify();//姓名
        $o_sex = new SexIdentify();//性别
        $o_id = new IdCardIdentify();//身份证号
        $o_number = new NumberIdentify();//电话号码
        $o_number2 = new NumberIdentify('电话2');//电话号码
        $o_trade = new TradesIdentify();//职业
        $o_character = new CharacterIdentify();//性格
        $o_hobby = new HobbyIdentify();//性格特点
        $a_data = [];
        while ($i_sign <= $i_nums):
            $o_name->decorate($o_person);
            $o_sex->decorate($o_name);
            $o_id->decorate($o_sex);
            $o_number->decorate($o_id);
            $o_number2->decorate($o_number);
            $o_trade->decorate($o_number2);
            $o_character->decorate($o_trade);
            $o_hobby->decorate($o_character);
            $a_tmp = [];
            $o_hobby->get($a_tmp);
            $a_data[] = $a_tmp;
            $i_sign++;
        endwhile;
        $a_data = array_map(function ($a_item) {
            $a_trades = explode('/', $a_item['行业']);
            $a_item['行业'] = $a_trades[0];
            array_splice($a_item, 6, 0, $a_trades[1]);
            array_splice($a_item, 2, 0, '身份证');
            //生日
            $s_birth = substr($a_item['身份证号'], 6, 8);
            $s_year = substr($s_birth, 0, 4);
            $s_month = substr($s_birth, 4, 2);
            $s_day = substr($s_birth, 6, 2);
            array_splice($a_item, 4, 0, $s_year . '-' . $s_month . '-' . $s_day);
            return array_values($a_item);
        }, $a_data);
        $o_excel = new Excel();
        $s_tail = ord('A') + count($a_data[0]) - 1;
        $a_customerInfo = config('customer_info');
        array_shift($a_customerInfo);//去除ID
        $a_fields = array_map(function ($a_item) {
            return $a_item[2];
        }, $a_customerInfo);
        $o_excel->export(
            range('A', chr($s_tail)),
            $a_fields,
            $a_data, '客户测试资料' . uniqid()
        );
        exit;

    }


    /**
     * 更改用户贷款号为已还款
     */
    public function returnLoan()
    {
        $i_id = input('id/d', 0);
        $a_data = Db::name('loan')->where('id', $i_id)->find();
        if ($a_data['is_return'] == 1):
            $this->error("该客户已经完成了还款！");
        endif;
        $o_m = new Loan;
        if (!$o_m->save(['is_return' => 1, 'return_time' => $_SERVER['REQUEST_TIME']], ['id' => $i_id])):
            $this->error("操作失败！");
        else:
            $this->success("已修改客户贷款状态为已还款！");
        endif;
    }

}